package com.atguigu.gulimall.ssoclient.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.List;

/**
 * @Author : Jungle
 * @Description :
 */
@Controller
public class HelloController {
    @Value("${sso.server.url}")
    private String ssoServerUrl;


    /**
     * 无需登录就可以访问
     * @return
     */
    @ResponseBody
    @GetMapping("/hello")
    public String hello(){
        return "hello";
    }


    /**
     * 感知这次是在ssoserver登录成功后跳回的
     * @param model
     * @param session
     * @param token  只要取ssoServer登录成功了就会带回来
     * @return
     */
    @GetMapping("/boss")
    public String employees(Model model, HttpSession session,@RequestParam(value = "token",required = false) String token) {
        if (!StringUtils.isEmpty(token)){
        //去ssoServer登录成功调回来就会带上
        //todo 去ssoServer获取当前token真正的对应的用户信息
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> forEntity = restTemplate.getForEntity("http://ssoserver.com:8080/userInfo?token=" + token, String.class);
            String userInfo = forEntity.getBody();

            session.setAttribute("loginUser", userInfo);
        }
        Object attribute = session.getAttribute("loginUser");
        if (attribute == null) {
            //    没登录,跳转到登录服务器进行登录
            //跳转过去以后，使用url上面的查询参数标识我们自己是哪个页面
            //redirect_url=http://client1.com:8081/employees
            return "redirect:"+ssoServerUrl+"?redirect_url=http://client2.com:8082/boss";
        } else {
            List<String> emps = Arrays.asList("张三", "李四");
            model.addAttribute("emps", emps);
            return "list";
        }

    }
}
